package com.summer.controller;

import com.summer.config.YouxinSMSConfig;
import com.summer.util.CallBackResult;
import com.summer.util.RedisUtil;
import com.summer.variable.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

@Slf4j
@RestController
@RequestMapping("/v1.0/api")
public class SendSMSController {

    @Resource(name = "youxinSMSConfig")
    private YouxinSMSConfig youxinSMSConfig;
    @Resource
    private RedisUtil redisUtil;
    /**
     * 获取手机验证码
     * @return
     */
    @GetMapping("/sms/{phoneNumber}")
    public Object sendPhoneCaptcha(@PathVariable("phoneNumber")
                                  @NotNull(message = "手机号"+Constant.PARAM_IS_NOT_BALANK)
                                  @Pattern(regexp = Constant.PHONE_REGULAR,message = Constant.PHONE_IS_ILLEGAL)
                                  String phoneNumber)throws Exception{
        log.info("start invoke UserLoginRegisterController  sendPhoneCaptcha phoneNumber={}", phoneNumber);
       if (redisUtil.hasKey(phoneNumber+Constant.PHONE_CAPTCHA_SUFFIX)){
            return new CallBackResult(Constant.RESULT_BAD_STATUS,"上次手机验证码还未失效,请使用上次发送的验证码！");
        }
            int mobile_code = (int)((Math.random()*9+1)*1000);
            String phoneCaptcha = String.valueOf(mobile_code);
            Boolean isSuccess = youxinSMSConfig.sendCode(phoneNumber, phoneCaptcha, Constant.SMS_TIRLE);
            if (isSuccess){
                redisUtil.set(phoneNumber + Constant.PHONE_CAPTCHA_SUFFIX,phoneCaptcha,Constant.PHONE_CAPTCHA_EXPIRATION_TIME);
                return new CallBackResult(CallBackResult.SUCCESS,"短信验证码发送成功！");
            }
         return  new CallBackResult(Constant.RESULT_BAD_STATUS,"短信验证码发送失败！");
    }
}
